(defun permutations (items &aux result)
   (if items
       (dolist (item items result)
        (dolist (permutation (permutations (remove item items)))
          (push (cons item permutation) result)))
       '(nil))) 

(defun multiples(n)
  (loop for i = (1+ (floor (/ 10.0 n))) then (1+ i)
       for p = (* i n)
       until (> p 1000)
       collect p))

(defun list-digits(n)
  (if (< n 10) (list n)
      (cons (mod n 10) (list-digits (floor (/ n 10))))))

(defun contains-duplicates(n)
  (= (length n) (length (remove-duplicates n))))

(defun make-no(l)
  (cond  ((= (length l) 1) (car l))
	 ((+ (car l) (* 10 (make-no (cdr l)))))))

(defun make-size (l)
  (if (= 3 (length l)) 
      l
      (append l '(0))))

(defun list-valid-multiples(n)
  (delete-if-not #'contains-duplicates
		 (mapcar #'make-size 
			 (mapcar #'list-digits 
				 (multiples n)))))

(defun is-match (a b)
  (and (= (nth 0 a) (nth (- (length b) 2) b))
       (= (nth 1 a) (nth (- (length b) 1) b))))

(defun combine(la lb)
  (cond ((null la) lb)
	((null lb) la)
	(t (loop for i in la 
	      with result = ()
	      do (setq result (append result 
				      (loop for j in lb
					 for r = (append i (cddr j))
					 when (and (is-match j i) (contains-duplicates r))
					 collect r)))
	      finally (return result)))))

(defun combine-no (noa nob)
  (combine (list-valid-multiples noa) (list-valid-multiples nob)))

(defun probl43(primes)
  (loop for i in primes 
     with k = nil
     do (setq k (combine k (list-valid-multiples i)))
     finally (return k)))

(defun difference (a b)
  (loop for i in a
       when (not (find i b))
       collect i))

(defun find-missing (x)
  (difference '(0 1 2 3 4 5 6 7 8 9) x))

(defun complete-no (x)
  (append x (find-missing x)))

(print 
 (mapcar #'make-no 
	 (mapcar #'complete-no 
		 (probl43 '(17 13 11 7 5 3 2)))))

(print 
 (reduce #'+ 
	 (mapcar #'make-no 
		 (mapcar #'complete-no 
			 (probl43 '(17 13 11 7 5 3 2))))))